using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using WpfMedia = System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
using System.Windows.Media;
using TxTReader.Core;
using TxTReader.Services;

namespace TxTReader.UI
{
    /// <summary>
    /// SearchWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SearchWindow : Window
    {
        private readonly SearchEngine _searchEngine;
        private readonly MainWindow _mainWindow;
        private SearchOptions _searchOptions;

        public event EventHandler<SearchResultSelectedEventArgs>? SearchResultSelected;

        public SearchWindow(SearchEngine searchEngine, MainWindow mainWindow)
        {
            InitializeComponent();
            
            // 设置窗口图标（搜索/放大镜图标）
            SetWindowIcon();
            
            _searchEngine = searchEngine;
            _mainWindow = mainWindow;
            _searchOptions = new SearchOptions();
            
            _searchEngine.SearchCompleted += OnSearchCompleted;
            _searchEngine.SearchProgress += OnSearchProgress;
            _searchEngine.SearchResultFound += OnSearchResultFound;
            
            // 订阅主题变化事件
            ThemeService.ThemeChanged += OnThemeChanged;
            
            // 在窗口加载完成后应用主题
            Loaded += (s, e) => ApplyTheme(ThemeService.GetCurrentTheme());
        }
        
        /// <summary>
        /// 窗口关闭时取消主题订阅
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            ThemeService.ThemeChanged -= OnThemeChanged;
            base.OnClosed(e);
        }
        
        /// <summary>
        /// 设置窗口图标（搜索/放大镜图标）
        /// </summary>
        private void SetWindowIcon(System.Drawing.Icon? icon = null)
        {
            try
            {
                // 创建搜索图标（放大镜）
                // 使用Path绘制：圆形 + 手柄
                var searchPath = "M13,6 C10.24,6 8,8.24 8,11 C8,13.76 10.24,16 13,16 C15.76,16 18,13.76 18,11 C18,8.24 15.76,6 13,6 Z M13,8 C14.66,8 16,9.34 16,11 C16,12.66 14.66,14 13,14 C11.34,14 10,12.66 10,11 C10,9.34 11.34,8 13,8 Z M17.29,15.71 L19.71,18.13 L17.29,15.71 Z M17.29,15.71 L15.71,17.29 L17.29,15.71 Z";
                var geometry = Geometry.Parse(searchPath);
                var drawing = new GeometryDrawing(
                    new SolidColorBrush(System.Windows.Media.Color.FromRgb(76, 175, 80)), // 绿色填充
                    new System.Windows.Media.Pen(new SolidColorBrush(System.Windows.Media.Color.FromRgb(56, 142, 60)), 1.5), // 深绿色边框
                    geometry);
                
                var drawingGroup = new DrawingGroup();
                drawingGroup.Children.Add(drawing);
                
                var drawingImage = new DrawingImage(drawingGroup);
                drawingImage.Freeze();
                
                // 将DrawingImage转换为BitmapSource并缩放为图标大小
                var renderTarget = new RenderTargetBitmap(32, 32, 96, 96, PixelFormats.Pbgra32);
                var visual = new DrawingVisual();
                using (var context = visual.RenderOpen())
                {
                    context.DrawImage(drawingImage, new Rect(0, 0, 32, 32));
                }
                renderTarget.Render(visual);
                renderTarget.Freeze();
                
                Icon = renderTarget;
            }
            catch
            {
                // 如果设置图标失败，使用系统默认图标
                try
                {
                    if (icon != null)
                    {
                        Icon = Imaging.CreateBitmapSourceFromHIcon(
                            icon.Handle,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());
                    }
                }
                catch { }
            }
        }
        
        /// <summary>
        /// 主题变化事件处理
        /// </summary>
        private void OnThemeChanged(ThemeInfo theme)
        {
            Dispatcher.Invoke(() => ApplyTheme(theme));
        }
        
        /// <summary>
        /// 计算与背景色对比鲜明的文本颜色
        /// </summary>
        private WpfMedia.Brush GetContrastColor(WpfMedia.Brush backgroundBrush)
        {
            if (backgroundBrush is WpfMedia.SolidColorBrush solidBrush)
            {
                var color = solidBrush.Color;
                // 计算相对亮度 (Rec. 709 标准)
                double luminance = 0.2126 * color.R / 255.0 + 0.7152 * color.G / 255.0 + 0.0722 * color.B / 255.0;
                
                // 如果背景较暗，使用亮色文本；如果背景较亮，使用暗色文本
                if (luminance < 0.5)
                {
                    // 背景较暗，使用亮色文本
                    return new WpfMedia.SolidColorBrush(WpfMedia.Color.FromRgb(255, 255, 255));
                }
                else
                {
                    // 背景较亮，使用暗色文本
                    return new WpfMedia.SolidColorBrush(WpfMedia.Color.FromRgb(0, 0, 0));
                }
            }
            // 如果不是SolidColorBrush，返回默认颜色
            return WpfMedia.Brushes.Black;
        }
        
        /// <summary>
        /// 应用主题
        /// </summary>
        private void ApplyTheme(ThemeInfo theme)
        {
            // 应用窗口背景
            Background = theme.WindowBackground;
            
            // 根据背景计算对比鲜明的文本颜色
            var contrastForeground = GetContrastColor(theme.WindowBackground);
            
            // 显式处理所有控件
            if (SearchTextBox != null)
            {
                SearchTextBox.Background = theme.WindowBackground;
                SearchTextBox.Foreground = contrastForeground;
                SearchTextBox.BorderBrush = contrastForeground; // 边框颜色与文本同色
                SearchTextBox.BorderThickness = new Thickness(1); // 确保边框始终显示
            }
            
            if (SearchResultsListBox != null)
            {
                SearchResultsListBox.Background = theme.WindowBackground;
                SearchResultsListBox.Foreground = contrastForeground;
                SearchResultsListBox.BorderBrush = contrastForeground; // 边框颜色与文本同色
                SearchResultsListBox.BorderThickness = new Thickness(1); // 确保边框始终显示
                
                // 为ListBox创建资源字典，让ItemTemplate中的TextBlock继承颜色
                var resources = new ResourceDictionary();
                resources["ContrastForeground"] = contrastForeground;
                SearchResultsListBox.Resources.MergedDictionaries.Add(resources);
                
                // 递归更新ListBox中所有TextBlock的颜色
                UpdateListBoxItemColors(SearchResultsListBox, contrastForeground);
            }
            
            // 显式处理特定控件
            if (ProgressText != null)
            {
                ProgressText.Foreground = contrastForeground;
            }
            
            if (ProgressDetails != null)
            {
                ProgressDetails.Foreground = contrastForeground;
            }
            
            // 处理按钮（包括边框和背景）
            if (SearchButton != null)
            {
                SearchButton.Foreground = contrastForeground;
                SearchButton.BorderBrush = theme.MenuBackground;
                SearchButton.Background = theme.MenuBackground;
            }
            
            if (StopButton != null)
            {
                StopButton.Foreground = contrastForeground;
                StopButton.BorderBrush = theme.MenuBackground;
                StopButton.Background = theme.MenuBackground;
            }
            
            if (CloseButton != null)
            {
                CloseButton.Foreground = contrastForeground;
                CloseButton.BorderBrush = theme.MenuBackground;
                CloseButton.Background = theme.MenuBackground;
            }
            
            // 递归应用主题到其他控件（Label、TextBlock、CheckBox等）
            ApplyControlTheme(this, contrastForeground, theme);
            
            // 处理GroupBox（包括边框）
            ApplyGroupBoxTheme(this, contrastForeground, theme);
        }
        
        /// <summary>
        /// 更新ListBox中所有项目的TextBlock颜色
        /// </summary>
        private void UpdateListBoxItemColors(ListBox listBox, WpfMedia.Brush contrastForeground)
        {
            if (listBox == null) return;
            
            // 遍历所有ListBoxItem
            for (int i = 0; i < listBox.Items.Count; i++)
            {
                var item = listBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                if (item != null)
                {
                    // 递归查找并更新TextBlock
                    ApplyControlTheme(item, contrastForeground, null);
                }
            }
        }
        
        /// <summary>
        /// 递归应用主题到GroupBox
        /// </summary>
        private void ApplyGroupBoxTheme(DependencyObject element, WpfMedia.Brush contrastForeground, ThemeInfo theme)
        {
            if (element == null) return;
            
            if (element is GroupBox groupBox)
            {
                groupBox.Foreground = contrastForeground;
                groupBox.Background = Background;
                groupBox.BorderThickness = new Thickness(0); // 不显示GroupBox边框
            }
            
            // 递归处理子元素
            int childCount = VisualTreeHelper.GetChildrenCount(element);
            for (int i = 0; i < childCount; i++)
            {
                var child = VisualTreeHelper.GetChild(element, i);
                ApplyGroupBoxTheme(child, contrastForeground, theme);
            }
        }
        
        /// <summary>
        /// 递归应用主题到控件
        /// </summary>
        private void ApplyControlTheme(DependencyObject element, WpfMedia.Brush contrastForeground, ThemeInfo theme)
        {
            if (element == null) return;
            
            // 应用Label和TextBlock的前景色（使用对比色）
            if (element is Label label)
            {
                label.Foreground = contrastForeground;
            }
            else if (element is TextBlock textBlock)
            {
                textBlock.Foreground = contrastForeground;
            }
            else if (element is CheckBox checkBox)
            {
                checkBox.Foreground = contrastForeground;
                if (theme != null)
                {
                    checkBox.BorderBrush = theme.MenuBackground;
                }
            }
            else if (element is TextBox textBox && theme != null)
            {
                // 处理其他TextBox的边框（SearchTextBox已经在ApplyTheme中处理）
                if (textBox != SearchTextBox)
                {
                    textBox.BorderBrush = theme.MenuBackground;
                    textBox.Background = theme.WindowBackground;
                    textBox.Foreground = contrastForeground;
                }
            }
            else if (element is Button button && theme != null)
            {
                // 处理其他按钮的边框和背景（已命名的按钮已经在ApplyTheme中处理）
                if (button != SearchButton && button != StopButton && button != CloseButton)
                {
                    button.Foreground = contrastForeground;
                    button.BorderBrush = theme.MenuBackground;
                    button.Background = theme.MenuBackground;
                }
            }
            
            // 递归处理子元素
            int childCount = VisualTreeHelper.GetChildrenCount(element);
            for (int i = 0; i < childCount; i++)
            {
                var child = VisualTreeHelper.GetChild(element, i);
                ApplyControlTheme(child, contrastForeground, theme);
            }
        }

        // XAML事件处理方法
        private async void OnSearchClick(object sender, RoutedEventArgs e)
        {
            await PerformSearch();
        }

        private async void OnSearchResultSelected(object sender, SelectionChangedEventArgs e)
        {
            if (SearchResultsListBox.SelectedItem is SearchResult result)
            {
                try
                {
                    System.Diagnostics.Debug.WriteLine($"SearchWindow.OnSearchResultSelected: 点击搜索结果，行号: {result.LineNumber}");
                    System.Diagnostics.Debug.WriteLine($"SearchWindow.OnSearchResultSelected: 行号类型: {result.LineNumber.GetType()}");
                    System.Diagnostics.Debug.WriteLine($"SearchWindow.OnSearchResultSelected: 行号值: {result.LineNumber}");
                    
                    // 直接调用主窗口的简化版跳转方法
                    bool jumpSuccess = await _mainWindow.JumpToLineAsync(result.LineNumber);
                    
                    if (jumpSuccess)
                    {
                        System.Diagnostics.Debug.WriteLine($"SearchWindow.OnSearchResultSelected: 跳转到第 {result.LineNumber} 行成功");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"SearchWindow.OnSearchResultSelected: 跳转到第 {result.LineNumber} 行失败");
                        // 不再显示MessageBox提示
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"SearchWindow.OnSearchResultSelected Error: {ex.Message}");
                    // 不再显示MessageBox提示，只在调试输出中记录错误
                }
                
                // 仍然触发事件，以防其他地方需要监听
                SearchResultSelected?.Invoke(this, new SearchResultSelectedEventArgs(result));
            }
        }

        private void OnCloseClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void OnStopClick(object sender, RoutedEventArgs e)
        {
            _searchEngine.StopSearch();
        }

        private async Task PerformSearch()
        {
            if (string.IsNullOrWhiteSpace(SearchTextBox.Text))
            {
                MessageBox.Show("请输入搜索内容", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            // 更新搜索选项
            _searchOptions.CaseSensitive = CaseSensitiveCheck.IsChecked ?? false;
            _searchOptions.WholeWord = WholeWordCheck.IsChecked ?? false;
            _searchOptions.UseRegex = false; // 不再支持正则表达式

            try
            {
                // 更新按钮状态
                SearchButton.IsEnabled = false;
                StopButton.IsEnabled = true;
                
                // 显示进度面板
                ProgressPanel.Visibility = Visibility.Visible;
                ProgressBar.Value = 0;
                ProgressText.Text = "正在搜索...";
                ProgressDetails.Text = "准备开始搜索";
                
                // 清空之前的结果，创建新的 ObservableCollection
                SearchResultsListBox.ItemsSource = new ObservableCollection<SearchResult>();
                
                await _searchEngine.SearchAsync(SearchTextBox.Text, _searchOptions);
            }
            catch (Exception ex)
            {
                // 隐藏进度面板
                ProgressPanel.Visibility = Visibility.Collapsed;
                MessageBox.Show($"搜索失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                // 恢复按钮状态
                SearchButton.IsEnabled = true;
                StopButton.IsEnabled = false;
            }
        }

        private void OnSearchCompleted(object sender, SearchCompletedEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                // 隐藏进度面板
                ProgressPanel.Visibility = Visibility.Collapsed;
                
                // 恢复按钮状态
                SearchButton.IsEnabled = true;
                StopButton.IsEnabled = false;
                
                // 由于使用 ObservableCollection 进行即时更新，这里不需要重新设置 ItemsSource
                // 只需要确保第一个结果被选中
                
                if (e.Results.Count > 0)
                {
                    SearchResultsListBox.SelectedIndex = 0;
                }
            });
        }

        private void OnSearchProgress(object sender, SearchProgressEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                // 显示进度面板
                ProgressPanel.Visibility = Visibility.Visible;
                
                // 更新进度条
                ProgressBar.Value = e.ProgressPercentage;
                
                // 更新进度文本
                ProgressText.Text = $"正在搜索... {e.ProgressPercentage:F1}%";
                
                // 更新详细信息
                ProgressDetails.Text = $"已处理 {e.ProcessedLines:N0} / {e.TotalLines:N0} 行";
            });
        }

        private void OnSearchResultFound(object sender, SearchResultFoundEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                // 使用 ObservableCollection 来避免频繁重新设置 ItemsSource
                if (SearchResultsListBox.ItemsSource is ObservableCollection<SearchResult> observableCollection)
                {
                    observableCollection.Add(e.Result);
                }
                else
                {
                    // 第一次添加结果时，创建 ObservableCollection
                    var observableResults = new ObservableCollection<SearchResult>();
                    observableResults.Add(e.Result);
                    SearchResultsListBox.ItemsSource = observableResults;
                }
                
                // 如果是第一个结果，自动选中
                if (SearchResultsListBox.Items.Count == 1)
                {
                    SearchResultsListBox.SelectedIndex = 0;
                }
                
                // 更新新添加项的颜色
                var contrastForeground = GetContrastColor(Background as WpfMedia.SolidColorBrush ?? WpfMedia.Brushes.White);
                var lastIndex = SearchResultsListBox.Items.Count - 1;
                if (SearchResultsListBox.ItemContainerGenerator.ContainerFromIndex(lastIndex) is ListBoxItem item)
                {
                    ApplyControlTheme(item, contrastForeground, null);
                }
            });
        }
    }
}